package com.ddwanglife.juc;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

class MyMap{
    private volatile Map<String,String> map = new HashMap<>();
    //这里有volatile修饰
    ReadWriteLock  rwl = new ReentrantReadWriteLock();

    public void put(String key,String value) throws InterruptedException {
        rwl.writeLock().lock();
        try{
            System.out.println(Thread.currentThread().getName()+"\t 开始插入数据");
            TimeUnit.MILLISECONDS.sleep(300);
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"\t 数据插入完成");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            rwl.writeLock().unlock();
        }

    }
    public String get(String key) throws InterruptedException {
        String value = null;
        rwl.readLock().lock();
        try{
            System.out.println(Thread.currentThread().getName()+"\t 开始查询数据");
            TimeUnit.MILLISECONDS.sleep(100);
            value = map.get(key);
            System.out.println(Thread.currentThread().getName()+"\t 数据查询完成");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            rwl.readLock().unlock();
        }
        return value;
    }
}
public class ReadWriteLockDemo {
    public static void main(String[] args) {
        MyMap mm = new MyMap();
        for (int i = 1; i <=10 ; i++) {
            new Thread(()->{
                try {
                    mm.put(Thread.currentThread().getName(),"");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },String.valueOf(i)).start();
        }
        for (int i = 1; i <=10 ; i++) {
            new Thread(()->{
                try {
                    mm.get(Thread.currentThread().getName());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },String.valueOf(i)).start();
        }
    }
}
